#coding=utf-8
from rest_framework import serializers
from rest_framework import viewsets
from rest_framework.decorators import api_view, detail_route, list_route
from rest_framework.response import Response
from django.contrib import admin
from worldcup.apps.userModel.models import Tracking


class TrackingSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Tracking
        fields = ('url', 'event', 'num')


class TrackingViewSet(viewsets.ModelViewSet):
    queryset = Tracking.objects.all()
    serializer_class = TrackingSerializer

    @list_route(methods=['post'])
    def push_event(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid()
        url = serializer.data["url"]
        event = serializer.data["event"]
        try:
            tracking = Tracking.objects.filter(url=url, event=event).get()
        except Tracking.DoesNotExist:
            tracking = Tracking(
                url=url,
                event=event,
                num=1
            )
            tracking.save()
        else:
            tracking.num += 1
            tracking.save()
        return Response({'ret': 0, 'content': 'success'})


class TrackingAdmin(admin.ModelAdmin):
    list_display = ('url', 'event', 'num')
